package com.pfzy.ui.utils;

import android.content.Context;
import android.text.TextUtils;

import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.file.LruDiskUsage;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.pfzy.ui.log.MyLog;
//import com.maitianshanglv.im.app.common.XUtils.XUtil;
//import com.maitianshanglv.im.app.common.log.MtLog;

import java.io.File;

/**
 * 音频缓存
 */
public class AudioCacheUtil {
    private static final int MAX_FILE_SIZE = 200;
    private static HttpProxyCacheServer mHttpProxyCacheServer;
    private static LruDiskUsage mLruDiskUsage;

    private static HttpProxyCacheServer getProxy(Context context) {
        if (mHttpProxyCacheServer == null) {
            mHttpProxyCacheServer = new HttpProxyCacheServer.Builder(context)
                    .cacheDirectory(getCacheDir())
                    .maxCacheFilesCount(MAX_FILE_SIZE)
                    .fileNameGenerator(new Md5FileNameGenerator())
                    .build();
        }
        return mHttpProxyCacheServer;
    }

    public static String getProxyUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        if (url.startsWith("http://") || url.startsWith("https://")) {
            HttpProxyCacheServer proxy = getProxy(CommonUtil.getContext());
            String proxyUrl = proxy.getProxyUrl(url);
            return proxyUrl;
        }
        return url;
    }

    /**
     * 获取缓存路径
     * @return
     */
    public static File getCacheDir() {
        File file = new File(CommonUtil.getContext().getCacheDir(), "im_cache");
        MyLog.logd("录音缓存 " + file.exists() + " "+ file.getPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取磁盘使用情况
     * @return
     */
    public static LruDiskUsage getLruDiskUsage() {
        if (mLruDiskUsage == null) {
            mLruDiskUsage = new TotalCountLruDiskUsage(MAX_FILE_SIZE);
        }
        return mLruDiskUsage;
    }

    /**
     * 已缓存
     * @param url
     * @return
     */
    public static boolean isCached(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        if (url.startsWith("http://") || url.startsWith("https://")) {
            HttpProxyCacheServer proxy = getProxy(CommonUtil.getContext());
            return proxy.isCached(url);
        }
        File file = new File(url);
        return file.exists();
    }
}
